# !/usr/bin/env python3
# coding=utf8
"""
读取通达信盘后数据文件, 并根据条件, 输出符合要求的数据,
"""


import argparse
import datetime
import os
import sys
import typing
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import tdxdata_converter  # NOQA: E402


def to_YmdHMS(src: bytes, suffix: str) -> datetime.datetime:
    """"""
    assert len(src) == 4

    if suffix == ".day":
        _val: int = tdxdata_converter.field_resolver.bytes_to_int(src)[0]
        dttm: datetime.datetime = tdxdata_converter.field_conv.yyyymmdd_to_datetime(
            arg1=tdxdata_converter.WrapPlain(_val)
        )
    else:
        _ddd: int = tdxdata_converter.field_resolver.bytes_to_unsignedshort(src[:2])[0]
        _ttt: int = tdxdata_converter.field_resolver.bytes_to_short(src[2:])[0]
        dttm: datetime.datetime = tdxdata_converter.field_conv.tdx_field_to_datetime(
            arg1=tdxdata_converter.WrapPlain(_ddd),
            arg2=tdxdata_converter.WrapPlain(_ttt)
        )
    return dttm


def show_content(filepath: str, condition: typing.Union[datetime.datetime, int, None]) -> None:
    """
    condition: 为空, 输出文件中的所有行的数据
    condition: 数字, 输出文件中的指定行的数据
    condition: 时间, 输出文件中的某时刻的数据
    condition: 列表, 输出文件中条件范围的数据
    """
    ROW_SIZE: int = 32
    COL_SIZE: int = 4

    suffix: str = os.path.splitext(filepath)[-1]

    all_content: bytes = b""
    try:
        with open(file=filepath, mode="rb") as f:
            all_content: bytes = f.read()
    except FileNotFoundError as ex:
        print(ex)

    assert len(all_content) % ROW_SIZE == 0

    _filedata: bytes = all_content
    _datcount: int = len(_filedata) // ROW_SIZE

    min_time: typing.Optional[datetime.datetime] = None
    max_time: typing.Optional[datetime.datetime] = None

    for r_idx in range(0, _datcount, 1):
        row_data: bytes = _filedata[r_idx * ROW_SIZE:(r_idx + 1) * ROW_SIZE]

        col_time: bytes = row_data[0 * COL_SIZE:(0 + 1) * COL_SIZE]

        cur_time: datetime.datetime = to_YmdHMS(col_time, suffix)

        min_time: datetime.datetime = min(min_time, cur_time) if min_time is not None else cur_time
        max_time: datetime.datetime = max(max_time, cur_time) if max_time is not None else cur_time

        if (
            isinstance(condition, (tuple, list)) and 1 <= len(condition) <= 2 and
            all(isinstance(_, int) for _ in condition) and
            not (condition[0] <= r_idx <= condition[-1])
        ):
            # condition = [3,]  # 仅打印第3条数据,
            # condition = [3, 7,]  # 打印第3~7条数据,
            continue

        if (
            isinstance(condition, (tuple, list)) and 1 <= len(condition) <= 2 and
            all(isinstance(_, datetime.datetime) for _ in condition) and
            not (condition[0] <= cur_time <= condition[-1])
        ):
            continue

        for c_idx in range(0, len(row_data) // COL_SIZE, 1):
            if c_idx == 0:  # 第 0 个字段是日期时间字段, (我是知道 range 可以从 1 开始的)
                continue

            col_data: bytes = row_data[c_idx * COL_SIZE:(c_idx + 1) * COL_SIZE]

            _i: int = tdxdata_converter.field_resolver.bytes_to_int(col_data)[0]
            _f: float = tdxdata_converter.field_resolver.bytes_to_float(col_data)[0]

            print("dttm={}, row={}, col={}, int={:<10}, float={:<22}".format(
                cur_time.strftime("%Y-%m-%d %H:%M:%S"), r_idx, c_idx, _i, _f)
            )
        print()  # 输出一个空行, 方便查看数据,

    print(f"count={_datcount}, min_time={min_time}, max_time={max_time}")


if __name__ == "__main__":
    filepath: str = r"C:\new_tdx\vipdoc\sh\lday\sh000300.day"  # 沪深300
    filepath: str = r"C:\new_tdx\vipdoc\sh\minline\sh000300.lc1"  # 沪深300
    filepath: str = r"C:\new_tdx\vipdoc\ds\minline\27#HSI.lc1"  # 恒生指数
    filepath: str = r"C:\new_tdx\vipdoc\ds\minline\31#00700.lc1"  # 腾讯控股
    filepath: str = r"C:\new_tdx\vipdoc\ds\minline\30#AUL8.lc1"  # 黄金主连
    filepath: str = r"C:\new_tdx\vipdoc\ds\minline\28#MAL8.lc1"  # 甲醇主连
    filepath: str = r"C:\new_tdx\vipdoc\ds\fzline\28#MAL8.lc5"  # 甲醇主连

    description = '注意: 文件里的"时间戳"是"交易日+自然时间", 不是"自然日+自然时间"!\n' +\
        "提示: 参数 condition 或许可以如下填写:\n" +\
        "--condition 3\n" +\
        "--condition 3 7\n" +\
        "--condition 2025-01-02T10:00:00\n" +\
        "--condition 2025-01-02T10:10:00 2025-01-02T10:40:00"

    parse = argparse.ArgumentParser(description=description, formatter_class=argparse.RawTextHelpFormatter)
    parse.add_argument('-f', '--file', type=str, required=True, help="文件路径")
    parse.add_argument('-c', '--condition', nargs='+', default=[], help="过滤条件")
    args = parse.parse_args()
    args.condition = [(int(_) if str.isdigit(_) else datetime.datetime.fromisoformat(_)) for _ in args.condition]

    show_content(filepath=args.file, condition=args.condition)

    print()
    print(f"file={args.file}, condition={args.condition}")
